using Devil;
using UnityEngine;

namespace GameToolkit.BehaviourTree
{
    [System.Serializable]
    [CompositeCategory("")]
    [CompositeTitle("黑板状态")]
    public class HasBlackboardValue : Composite
    {
        enum VariableState
        {
            IsSetting,
            IsNotNull,
            IsNotSetting,
            IsNull,
        }

        [SerializeField]
        string m_VariableName;

        [SerializeField]
        VariableState m_VariableState;

        public override string GetDescription()
        {
            if (string.IsNullOrEmpty(m_VariableName))
                return "Invalid Blackboard State";
            var title = ParallelUtils.ToCamelName(m_VariableState.ToString(), true);
            return $"<{m_VariableName}> {title}";
        }

        public override BehaviourTreeObject Create()
        {
            return new Impl();
        }

        class Impl : Condition
        {
            public override bool IsTrue(BehaviourTreePlayer player/*, ExecutableEntry attachNode*/)
            {
                var cfg = (HasBlackboardValue)composite;
                object value;
                switch(cfg.m_VariableState)
                {
                    case VariableState.IsSetting:
                        return !string.IsNullOrEmpty(cfg.m_VariableName) && player.Executable.IsBlackboardSet(cfg.m_VariableName);
                    case VariableState.IsNotSetting:
                        return !string.IsNullOrEmpty(cfg.m_VariableName) && !player.Executable.IsBlackboardSet(cfg.m_VariableName);
                    case VariableState.IsNotNull:
                        return !string.IsNullOrEmpty(cfg.m_VariableName) && player.Executable.GetBlackboard(cfg.m_VariableName, out value) && value != null;
                    case VariableState.IsNull:
                        return !string.IsNullOrEmpty(cfg.m_VariableName) && (!player.Executable.GetBlackboard(cfg.m_VariableName, out value) || value == null);
                    default:
                        return false;
                }
            }

            protected override void OnCreate(BehaviourTreePlayer player)
            {
            }

            protected override void OnDestroy(BehaviourTreePlayer player)
            {
            }
        }

    }
}
